package bill;

import models.BaseModel;
import models.constants.DeletedStatus;
import models.constants.SuccessStatus;
import models.merchant.Merchant;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import play.modules.paginate.JPAExtPaginator;

import javax.persistence.*;
import java.util.Date;
import java.util.Map;

/**
 * 商户提现表
 */
@Entity
@Table(name = "withdrawals_bills")
public class WithdrawalsBill extends BaseModel {

    /**
     * 提现编号
     */
    @Column(name = "bill_code")
   public String billCode;

    /**
     * 关联商户
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;


    /**
     * 金额
     */
    @Column(name = "amount")
    public Integer amount;


    /**
     * 是否成功,0:成功，1:失败
     */
    @Enumerated(EnumType.ORDINAL)
    public SuccessStatus successStatus;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 备注信息
     */
    @Column(name = "remark")
    public String remark;


    public WithdrawalsBill() {
        super();
    }

    public WithdrawalsBill(Merchant merchant , Integer amount) {
        this.billCode = DateFormatUtils.format(new Date(), "yyMMdd") + RandomStringUtils.randomNumeric(9);
        this.merchant = merchant;
        this.amount = amount;
        this.successStatus = SuccessStatus.WAIT;
        this.createAt = new Date();
        this.deleted = DeletedStatus.UN_DELETED;
    }

    /**
     * 根据编号查询交易记录
     * @param orderNumber
     * @return
     */
    public static WithdrawalsBill findByOrderNumber(String orderNumber) {
        return WithdrawalsBill.find("deleted = ?1 and billCode = ?2" , DeletedStatus.UN_DELETED , orderNumber).first();
    }


    /**
     * 分页查询.
     */
    public static JPAExtPaginator<WithdrawalsBill> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder("t.deleted=models.constants.DeletedStatus.UN_DELETED ")
                .append("/~ and t.merchant.id = {merId} ~/")
               .append("/~ and t.createAt >= STR_TO_DATE({startTime},'%Y-%m-%d %H:%i:%s') ~/")
                .append("/~ and t.createAt <= STR_TO_DATE({endTime},'%Y-%m-%d %H:%i:%s') ~/");


        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        JPAExtPaginator<WithdrawalsBill> orderPage = new JPAExtPaginator<WithdrawalsBill>("WithdrawalsBill t", "t", WithdrawalsBill.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        orderPage.setPageNumber(pageNumber);
        orderPage.setPageSize(pageSize);
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }







}
